package copyengine.ui.component.tabbar
{
	import flash.display.DisplayObjectContainer;

	import copyengine.ui.component.CEUISprite;
	import copyengine.ui.component.button.CEButton;
	import copyengine.ui.component.button.CESelectableButton;
	import copyengine.ui.component.tabbar.animation.ICETabBarAnimation;
	import copyengine.utils.GeneralUtils;

	public final class CETabBar extends CEUISprite
	{
		private var animation:ICETabBarAnimation;

		private var currentTab:String;

		private var subBtnsVector:Vector.<CESelectableButton>

		private var onTabbarChangeCallBackFunction:Function

		/**
		 * Tabbar组件,由多个按钮组成的元件集合体
		 *
		 * @param _targetMc													目标元件Mc(该MC中包含多个按钮子集)
		 * @param _subBtnsVector											所有按钮Vector(按钮由外部进行初始化好,Tabbar内部仅设置一次onClickCallback)
		 * @param _onTabbarChangeCallBackFunction			当Tabbar的标签被切换时候回调该函数
		 *
		 */
		public function CETabBar(_targetMc:DisplayObjectContainer)
		{
			super(_targetMc);
		}

		/**
		 * 设置Tabbar默认的Tab签,
		 * 在第一次调用时候不会回调Callback(判断currentTab是否为null)
		 */
		public function initialzie(_defaultTab:String,
								   _subBtnsVector:Vector.<CESelectableButton>,
								   _onTabbarChangeCallBackFunction:Function=null):void
		{
			currentTab=_defaultTab;
			subBtnsVector=_subBtnsVector;
			onTabbarChangeCallBackFunction=_onTabbarChangeCallBackFunction;

			//设置按钮初始状态
			for each (var btn:CESelectableButton in subBtnsVector)
			{
				btn.clickToSelect=false;
				btn.selected=btn.name == currentTab;
				btn.setOnClickCallBackFunction(onClickSubBtn);
			}
			animation && animation.setDefaultSelectedTab(currentTab);
		}

		override protected function doDispose():void
		{
			animation && animation.dispose();
			while (subBtnsVector.length > 0)
			{
				var btn:CESelectableButton=subBtnsVector.pop();
				GeneralUtils.removeTargetFromParent(btn);
			}
			subBtnsVector=null;
		}

		public function setAnimation(_animation:ICETabBarAnimation):void
		{
			animation=_animation;
		}

		public function getCurrentTab():String
		{
			return currentTab;
		}

		private function onClickSubBtn(_targetBtn:CEButton):void
		{
			var clickedBtnName:String=_targetBtn.name;
			if (currentTab != clickedBtnName)
			{
				currentTab=clickedBtnName;
				for each (var btn:CESelectableButton in subBtnsVector)
				{
					btn.selected=btn.name == clickedBtnName;
				}
				animation && animation.changeSelected(clickedBtnName);
				onTabbarChangeCallBackFunction && onTabbarChangeCallBackFunction(currentTab)
			}
		}
	}
}
